package org.uva.streambuilder;

import java.applet.*;
import java.awt.*;
import java.awt.event.*;


public class StreamSocket implements 
 	MouseListener, MouseMotionListener
{
    int width, height;
    int x, y;
    int mx, my;
    boolean isMouseDraggingBox = false, mouseOver = false;
    int bx = 10, by = 10;
    Applet applet;
    static int snap = 10;
    String name;
    Font font;
    Color selectColor;
    Color defaultColor;
    StreamModule parent;
    boolean selected = false;
    boolean creatingConnector = false;
    int startx, starty;
    
    static int id = 0;

    public StreamSocket (Applet app, StreamModule parent, int x, int y)
    {
	id++;
	name = "Module " + id;
	applet = app;
	this.parent = parent;
	//this.x = x-bx/2; this.y = y-by/2;
	this.x = x;
	this.y = y;
	applet.addMouseListener( this );
	applet.addMouseMotionListener( this );

	font = new Font("Monospace", Font.PLAIN, 10);
	defaultColor = Color.black;
	selectColor = Color.red;

    }    

    boolean isClicking(int mx, int my)
    {
	if ( parent.x + x < mx && mx < parent.x + x +bx && parent.y + y< my && my < parent.y + y+by)
	    return true;
	else
	    return false;
    }
    
    boolean isClicking(MouseEvent e)
    {
    	return isClicking(e.getX(),e.getY());
    }


    public void draw( Graphics g )
    {
    	if (selected) {
    		g.setColor(selectColor);

    	}
    	else {
    		g.setColor(defaultColor);
    	}
    	
    	g.fillOval(parent.x + x, parent.y + y, bx, by);
    	
    	if (creatingConnector)
    	{
    		g.setColor(Color.white);
    		g.drawLine(startx, starty, startx, my);
    		g.drawLine(startx, my, mx, my);
    		
    	}
		
    }

    public void mouseEntered( MouseEvent e ) {}
    public void mouseExited (MouseEvent e ) {}
    public void mouseClicked( MouseEvent e ) {}
    public void mousePressed ( MouseEvent e ) {
	mx = e.getX();
	my = e.getY();
	
	if (!creatingConnector && isClicking(e)) {
		creatingConnector = true;
		startx = mx;
		starty = my;
	}
	
	e.consume();
    }

    public void mouseReleased (MouseEvent e ) {
    	
    	creatingConnector = false;
    	startx = 0; starty = 0;
	e.consume();
    }
    public void mouseMoved( MouseEvent e ) {
    	if (isClicking(e.getX(), e.getY()))
    	{
    		selected = true;
    	}
    	else
    		selected = false;
    	//applet.repaint();
    	
    }

    public void mouseDragged( MouseEvent e ) {
	    //applet.repaint();
	    
    	mx = e.getX();
    	my = e.getY();
    	
    	e.consume();

    }
}
